package fun.boomcat.luckyhe.mirai.plugin.command;

import fun.boomcat.luckyhe.mirai.plugin.utils.OpMcCommandHelp;
import fun.boomcat.luckyhe.mirai.plugin.utils.RconUtil;
import kotlin.Unit;
import kotlin.coroutines.Continuation;
import net.kronos.rkon.core.ex.AuthenticationException;
import net.mamoe.mirai.console.command.CommandManager;
import net.mamoe.mirai.console.command.CommandOwner;
import net.mamoe.mirai.console.command.CommandSender;
import net.mamoe.mirai.console.command.RawCommand;
import net.mamoe.mirai.console.permission.Permission;
import net.mamoe.mirai.message.data.MessageChain;
import net.mamoe.mirai.message.data.SingleMessage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;

public class OpMcCommand extends RawCommand {

    public OpMcCommand(@NotNull CommandOwner owner, @NotNull String primaryName, @NotNull String[] secondaryNames, @NotNull String usage, @NotNull String description, @NotNull Permission parentPermission, boolean prefixOptional) {
        super(owner, primaryName, secondaryNames, usage, description, parentPermission, prefixOptional);
    }

    @Nullable
    @Override
    public Object onCommand(@NotNull CommandSender commandSender, @NotNull MessageChain messageChain, @NotNull Continuation<? super Unit> continuation) {
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();
        String primaryName = this.getPrimaryName();

        int mcLen = messageChain.toArray().length;
        if (mcLen == 0) {
            commandSender.sendMessage(OpMcCommandHelp.opMcHelp(commandPrefix, primaryName));
            return null;
        }

        StringBuilder sb = new StringBuilder();

        for (SingleMessage singleMessage : messageChain) {
            sb.append(singleMessage.contentToString()).append(" ");
        }

        String res;

        try {
            res = RconUtil.sendMcCommand(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            commandSender.sendMessage("错误：请检查rcon连接地址或mc服务器状态");
            return null;
        }

        commandSender.sendMessage("返回结果：\n" + res);

        return null;
    }
}
